package com.foreknow.service.impl;

import com.foreknow.bean.Guestbook;
import com.foreknow.dao.GuestbookDao;
import com.foreknow.dao.impl.GuestbookDaoImpl;
import com.foreknow.db.DBManager;
import com.foreknow.service.GuestbookService;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class GuestbookServiceImpl implements GuestbookService {

    @Override
    public List<Object> getAll() {
        DBManager dbManager = DBManager.getInstance();
        GuestbookDaoImpl guestbookDao = new GuestbookDaoImpl();
        guestbookDao.setConnection(dbManager.getConnection());
        List<Object> list = null;
        try {
            list = guestbookDao.getAllMessage();

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public boolean deleteBean(Integer id) {
        DBManager dbManager = DBManager.getInstance();
        GuestbookDaoImpl guestbookDao = new GuestbookDaoImpl();
        Connection conn = dbManager.getConnection();
        guestbookDao.setConnection(conn);
        boolean isRight = false;
        try {
            isRight = guestbookDao.deleteById(id);
            conn.commit();
        } catch (SQLException e) {
            try {
                conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }

        return isRight;
    }

    @Override
    public boolean add(Guestbook gb) {
        DBManager dbManager = DBManager.getInstance();
        GuestbookDaoImpl guestbookDao = new GuestbookDaoImpl();
        Connection conn = dbManager.getConnection();
        guestbookDao.setConnection(conn);
        boolean isRight = false;
        try {
            isRight = guestbookDao.save(gb);
            conn.commit();//提交事物
        } catch (SQLException e) {
            try {
                conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }
        return isRight;
    }


}
